package com.cbn.ibcp.framework.aspectj;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.cbn.ibcp.common.annotation.DataSource;
import com.cbn.ibcp.common.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * 多数据源处理
 *
 * @author xuelianyong
 */
@Aspect
@Order(1)
@Component
public class DataSourceAspect {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.cbn.ibcp.common.annotation.DataSource)" + "|| @within(com.cbn.ibcp.common.annotation.DataSource)")
    public void dsPointCut() {

    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        String tenantCode = getDataSourceName(point);
        if (StringUtils.isNotNull(tenantCode)) {
            DynamicDataSourceContextHolder.push(tenantCode);
        }
        try {
            return point.proceed();
        } finally {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clear();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public String getDataSourceName(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        String[] parameterNames = signature.getParameterNames();
        Object[] args = point.getArgs();
        String tenantCode = null;
        if (ArrayUtil.isNotEmpty(parameterNames) && ArrayUtil.isNotEmpty(args) && parameterNames[0].equals("tenantCode")) {
            tenantCode = StrUtil.toStringOrNull(args[0]);
        }
        if (StrUtil.isNotBlank(tenantCode)) {
            return tenantCode;
        }
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource)) {
            return dataSource.value().name();
        }
        return null;
    }
}
